package com.boot.dog.web.security.component;

import cn.hutool.core.util.StrUtil;
import com.boot.dog.common.constant.SecurityConst;
import com.boot.dog.mapper.PermissionMapper;
import com.boot.dog.service.PermissionService;
import lombok.AllArgsConstructor;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.util.*;

/**
 * @Author: MaxLv
 * @Date: 2019/12/2
 */
@Component
@AllArgsConstructor
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private final PermissionMapper permissionMapper;

    private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

    private void loadResourceDefine() {

        resourceMap = new HashMap<>();
        Collection<ConfigAttribute> configAttributes = new ArrayList<>();
        permissionMapper.findByTypeAndStatusOrderBySortOrder(
                SecurityConst.PERMISSION_OPERATION, SecurityConst.PERMISSION_STATUS_NORMAL).stream().forEach(permission -> {
            if (StrUtil.isNotBlank(permission.getTitle()) && StrUtil.isNotBlank(permission.getPath())) {
                configAttributes.add(new SecurityConfig(permission.getTitle()));
                resourceMap.put(permission.getPath(), configAttributes);
            }
        });
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        loadResourceDefine();
        PathMatcher pathMatcher = new AntPathMatcher();
        String url = ((FilterInvocation) o).getRequestUrl();
        for (String resUrl : resourceMap.keySet()) {
            if (StrUtil.isNotBlank(resUrl) && pathMatcher.match(resUrl, url)) {
                return resourceMap.get(resUrl);
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
